package se.webbzon.boltzmann.game.sequence.builder.assignment;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;

import se.webbzon.boltzmann.game.sequence.builder.SequenceBuilder;
import se.webbzon.boltzmann.game.sequence.builder.SequenceRowDeflation;
import se.webbzon.oschi01.friendly.Friendly;

public class AssignmentRowDeflation implements SequenceRowDeflation {
	
	private String variable, expression;

	/*============================================================
	Constructors
	============================================================*/
	
	public AssignmentRowDeflation() {};
	
	public AssignmentRowDeflation(AssignmentRow row) {
		variable = row.getVariable();
		expression = row.getExpression();
	}
	
	/*============================================================
	Public Methods
	============================================================*/
	
	@Override public void inflate(ByteBuffer buff) {
		// Read from buffer
		byte[] variableData = new byte[buff.getShort()];
		buff.get(variableData, 0, variableData.length);
		byte[] expressionData = new byte[buff.getShort()];
		buff.get(expressionData, 0, expressionData.length);
		
		// Decode strings
		try {
			variable = new String(variableData,"UTF-8");
		} catch (UnsupportedEncodingException e) {
			variable = "";
		}
		
		try {
			expression = new String(expressionData,"UTF-8");
		} catch (UnsupportedEncodingException e) {
			expression = "";
		}
	}

	@Override public ByteBuffer deflate(int allocate) {
		byte[] variableData, expressionData;
		
		// Encode strings
		try {
			variableData = variable.getBytes("UTF-8");
		} catch (UnsupportedEncodingException e) {
			variableData = new byte[0];
		}
		
		try {
			expressionData = expression.getBytes("UTF-8");
		} catch (UnsupportedEncodingException e) {
			expressionData = new byte[0];
		}
		
		ByteBuffer buff = ByteBuffer.allocate(	allocate + 4 + 
												variableData.length + 
												expressionData.length);
		
		// Write to buffer
		buff.putShort((short) variableData.length);
		buff.put(variableData);
		buff.putShort((short) expressionData.length);
		buff.put(expressionData);
		
		return buff;
	}
	
	/*============================================================
	Friendly Methods
	============================================================*/
	
	/** Returns the inflated assignment row of this deflation. **/
	@Friendly AssignmentRow makeRow(SequenceBuilder builder) {
		return new AssignmentRow(builder,variable,expression);
	}

}
